import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useFabricColumns } from '../TableColumns'
import { SupplierColorStockPageVO as ITableData } from '../types'
import CustomTable from '@/components/QsfCustomTable'
import { useNavigate } from 'react-router-dom'
import { searchConfigOfFabric } from '../FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import '../index.less'
import useCachePage from '@/hooks/useCachePage'
import { getSupplierColorFabricStock } from '@/api/fabric'
import { Button, Checkbox, Form, Spin } from 'antd'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
const Index: React.FC = () => {
  const [form] = useForm()
  const ProDevSeason = useGetProDevSeason()
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { setCachePage, getCachePage } = useCachePage()
  const [tableData, settableData] = useState<ITableData[]>([])
  const [spinning, setspinning] = useState(false)
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getSupplierColorFabricStock, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      onlyHasStock: ['onlyHasStock'],
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        onlyHasStock: reqParams.onlyHasStock && reqParams.onlyHasStock.length > 0 ? 1 : 0,
      }
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  useEffect(() => {
    settableData(tableProps?.dataSource?.sort((a: any, b: any) => a?.fabricCode.localeCompare(b?.fabricCode)) || [])
  }, [tableProps.dataSource])
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      reload({ ...resetCacheData })
    }
  }
  return (
    <PageContainer className="fabric_stock_wrap">
      <SearchForm
        className="StockOfFabric"
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfigOfFabric({
          SupplierOption,
          handleSearchSupplier,
          ProDevSeason,
        })}
        onFinish={async () => {
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset()
          setCachePage({
            current: 1,
            size: 10,
            onlyHasStock: ['onlyHasStock'],
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <Form form={form}>
                <Form.Item noStyle name="onlyHasStock">
                  <Checkbox.Group
                    disabled={tableProps.loading}
                    onChange={(onlyHasStock) => {
                      const cacheData = getCachePage()
                      setCachePage({
                        ...cacheData,
                        onlyHasStock,
                        current: 1,
                      })
                      search()
                    }}
                    options={[
                      {
                        label: '只看有库存的面料',
                        value: 'onlyHasStock',
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
            </div>
            <div className="table_extra_flex"></div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        stripe={false}
        isAutoScrollY
        {...tableProps}
        columns={useFabricColumns({ tableData })}
        rowKey={(rows) =>
          rows?.fabricCode +
          (rows?.supplierCode || '') +
          (rows?.fabricName || '') +
          (rows?.useSite || '') +
          (rows?.currentColorFabricStockQty || '') +
          (rows?.fabricColorCode || '')
        }
        searchFormClassName="StockOfFabric"
        extraHeight={36}
      ></CustomTable>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
